package com.ruoyi.app.service;

import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringRandomUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @author cyh
 * @date 2022/6/29 4:35 下午
 */
@Slf4j
@Service
@AllArgsConstructor
public class InviteCodePool {

    private RedisCache redisCache;

    private IAppUserService appUserService;

    /**
     * 分配邀请码
     *
     * @return
     */
    public String assignInviteCode(boolean checkUse) {
        long size = redisCache.listSize(RedisCache.INVITE_CODE_QUEUE);
        log.info("assignInviteCode:{}",size);
        String inviteCode = redisCache.ListLeftPop(RedisCache.INVITE_CODE_QUEUE).toString();
        //是否已被使用
        if (checkUse && !appUserService.getInviteCOdeCount(inviteCode)) {
            return this.assignInviteCode(true);
        }
        return inviteCode;
    }

    /**
     * 初始化100w
     *
     * @return
     */
    public Long initialization() {
        Long listSize = redisCache.listSize(RedisCache.INVITE_CODE_QUEUE);
        log.info("inviteCodeList...size:{}", listSize);
        if (listSize > 0) {
            return 0L;
        }
        //100w
        Set inviteCodeList = new HashSet<>();
        for (int i = 0; i < 1100000; i++) {
            if (inviteCodeList.size() == 1000000) break;
            inviteCodeList.add(StringRandomUtils.genRandomNum());
        }
        return redisCache.rightPushAll(RedisCache.INVITE_CODE_QUEUE, inviteCodeList);
    }

}
